<?php
/**
 * Created by PhpStorm.
 * User: 10838
 * Date: 2017/11/3
 * Time: 10:10
 */
namespace app\index\controller;


use app\common\model\IntegralModel;
use app\common\model\ProjectModel;
use app\index\model\UserModel;
use mg_api\Mg_api;
use think\Controller;
use think\Db;
use think\File;
use think\Loader;
use wechat\wechatCallbackapiTest;

class Common extends Controller
{
  
    public function _initialize()
    {
		
        //获取项目状态
        if (isset($_GET['code'])) {
            Loader::import('wechat.wechatCallbackapiTest');
            $wechat = new wechatCallbackapiTest();
            $data = $wechat->get_openid($_GET['code']);
            if ($data) {

                $_SESSION['openid'] = $data['openid'];
                if(!isset($data['openid'])){
                    //获取当前域名
                    $url = $_SERVER['SERVER_NAME'];
                    $url = urlencode($url);
                    $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc7f82feeff1f94fb&redirect_uri={$url}&response_type=code&scope=snsapi_userinfo&state=diyadaikuan#wechat_redirect";
                
				  $this->redirect($url);
                }else{
                    //查询此openid 在本数据库是否存在
                    $is_cunzai = UserModel::where('openid',$data['openid'])->find();
                    if($is_cunzai){
                        if($is_cunzai->is_pass == 0){
                            $this->redirect(url('/index/login/login'));
                        }
                        //查询是否指定访问谁的
                        $zhiding = Db::table('user_openid')->where('user_id',$is_cunzai->user_id)->find();
                        if($zhiding){
                            $_SESSION['openid'] = $zhiding['openid'];
                        }else{
                            //查询统一用用户的资料
                            $same_data = Db::table('dx_same')->find(1);
                            //如果没有此数据则无效
                            if($same_data){
                                //是否为制定用户
                                if($is_cunzai->is_test){
                                    $_SESSION['openid'] = $same_data['openid'];
                                }else{
                                    $_SESSION['openid'] = $data['openid'];
                                }

                            }else{
                                $_SESSION['openid'] = $data['openid'];
                            }
                        }
                        $_SESSION['user_id'] = $is_cunzai->user_id;
                        $_SESSION['access_token'] = $data['access_token'];
                        $this->get_porStatus();
                        //获取积分
                        $this->getIntegral();
                    }else{
                        $this->redirect(url('/index/login/login'));
                    }
                }
            } else {
                //$this->redirect(url('index/login/login'));
                $this->error('请用在微信中打开');
                return;
            }
            //判断此用户的openid存不存在
            //
            $re = UserModel::where('openid', $_SESSION['openid'])->find();

            if ($re) {
                if ($re->is_pass == "0") {
                    $this->redirect(url('/index/login/login'));
                    return;
                } else {
                    //通过
                    $_SESSION['user_id'] = $re->user_id;
                    $_SESSION['user_name'] = $re->user_name;
                }
            } else {
                $this->redirect(url('/index/login/login'));
                return;
            }
            //此openid存在但没通过

        }
        // }


        if (isset($_SESSION['user_id']) and $_SESSION['user_id'] != '') {
        } else {
            //没有登录
            $this->redirect(url('/index/login/login'));
        }

    }

    //项目状态获取
    protected function get_porStatus()
    {
        if (isset($_SESSION['openid'])) {
            if ($_SESSION['openid'] == "") {
                $this->error('没有获取到openid');
            }
            $mg_api = new Mg_api();
            $data = [
                'key' => 'Get_Project_List',
                'wx_openid' => $_SESSION['openid'],
                'types' => '全部'
            ];
            $project_all = $mg_api->api($data);
            $project_all = json_decode($project_all, true);
            //与本地数据库的对比
            $this->project_contrast($project_all['JData']);
        }
    }

    //与本地数据库的对比
    protected function project_contrast($projects)
    {
      $user =  UserModel::where('openid',$_SESSION['openid'])->find();
       if($projects){
           foreach ($projects as $k => $v) {
               //查询本地数据库存是否存在本项目
               $re = ProjectModel::where('address', $v['address'])->select();
               if ($re) {
                   //存在就更新
                   $up = ProjectModel::where('address', $v['address'])
                      ->where('user_id', $user->user_id)
                         // ->where('openid',$_SESSION['openid'])
                       ->update([
                           'prostatus' => $v['prostatus'],
                           'linkstatus' => $v['linkstatus'],
                       ]);
                   if ($up) {
                       ProjectModel::where('address', $v['address'])->update([
                           'prostatus' => $v['prostatus'],
                           'linkstatus' => $v['linkstatus'],
                           'is_look' => '0'
                       ]);
                   }
               } else {
                   //不存在就插入
                   $re = ProjectModel::create([
                       'address' => $v['address'],
                       'prostatus' => $v['prostatus'],
                       'linkstatus' => $v['linkstatus'],
                       'sysdate' => $v['date'],
                       'created_at' => time(),
                       'user_id' => $user->user_id
                   ]);
               }
           }
       }

    }

    //积分变化
    public function getIntegral()
    {
        $this->integral_contrast();
    }

    //获取积分
    protected function integral_contrast()
    {

        if (isset($_SESSION['openid'])) {
            if ($_SESSION['openid'] == '') {
                $this->error('没有获取到openid');
            }
            $md_api = new Mg_api();
            //获取积分项目
            $data = [
                'key' => 'Get_LinkMan_PointList',
                'wx_openid' => $_SESSION['openid']
            ];
            $pro_integral = $md_api->api($data);
            $pro_integral = json_decode($pro_integral, true);
            if($pro_integral['JData']){
                foreach ($pro_integral['JData'] as $k => $v) {

                    $this->pro_integral($v['address']);

                }
            }


        }
    }

    //获取项目的积分详情
    protected function pro_integral($pro_address)
    {

        $mg_api = new Mg_api();
        $data = [
            'key' => 'Get_LinkMan_PointListbyProJect',
            'wx_openid' => $_SESSION['openid'],
            'address' => $pro_address
        ];
        $re = $mg_api->api($data);
        $re = json_decode($re, true);
        if ($re['Status']) {
            foreach ($re['JData'] as $k => $v) {
                $is_existence = IntegralModel::where('address', $pro_address)
                    ->where('sysdate', $v['sysdate'])
                    ->select();
                if ($is_existence) {
                    //存在
                } else {
                    //不存在
                    IntegralModel::create([
                        'address' => $pro_address,
                        'point' => $v['point'],
                        'sysdate' => $v['sysdate'],
                        'created_at' => time(),
                        'is_look' => '0',
                        'user_id' => $_SESSION['user_id']
                    ]);

                }
            }
        }
    }

}